package com.tiantian.novel.helper;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * Jar utils
 *
 * @author wangkai
 * @since 2020/12/18.
 */
public class JarHelper {
    private static final Logger log = LoggerFactory.getLogger(JarHelper.class);
    /**
     * 是否覆盖同名文件
     */
    private boolean override = false;

    private JarHelper(boolean override) {
        this.override = override;
    }

    public static JarHelper getInstance() {
        return new JarHelper(false);
    }

    public static JarHelper getInstance(boolean override) {
        return new JarHelper(override);
    }

    /**
     * 复制jarFile中的【src】到【dest】
     *
     * @param jarFile
     * @param folderName
     * @param destDir
     */
    public void copyFolder(String jarFile, String folderName, String destDir) throws IOException {
        log.info("copyFolder in【{}】,from【{}】to【{}】", jarFile, folderName, destDir);
        if (!jarFile.startsWith("file:")) {
            log.info("Not found A jar file,{}", jarFile);
            _copyDirectory(jarFile.substring(1), folderName, destDir);
            return;
        }

        jarFile = _substringBetween(jarFile, "file:", "!");
//        String dest = destDir + File.separator + folderName;
        String dest = destDir;
        log.info("copy From Jar【{}】,【{}】to【{}】", jarFile, folderName, dest);
        _unCompress(new File(jarFile), new File(dest), folderName);
    }

    private void _copyDirectory(String srcDir, String folderName, String destDir) throws IOException {
        String src = srcDir + folderName;
//        String dest = destDir + File.separator + folderName;
        String dest = destDir;
        log.info("_copyDirectory from【{}】to【{}】", src, dest);
        FileUtils.copyDirectory(new File(src), new File(dest));
    }

    public static void main(String[] args) throws IOException {
        String s1 = "file:/D:/git/javase/novel/target/novel-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/";
//        String s2 = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
        s1 = "file:/workspace/app/mynovel/linux/novel-0.0.1-SNAPSHOT_linux_9.jar!/BOOT-INF/classes!/";
        System.out.println(s1);
        String s3 = _substringBetween(s1, "file:", "!");
        System.out.println(s3);
    }

    /**
     * 解压Jar文件
     *
     * @param jarFile                     指定jar文件
     * @param targetDir                   指定解压文件夹
     * @param includePath：要拷贝的前缀，过滤不需要的文件
     * @throws IOException 抛出异常
     * @throws IOException
     */
    public void _unCompress(File jarFile, File targetDir, String includePath) throws IOException {
        log.info("_unCompress({},{},{})", jarFile, targetDir, includePath);
        JarFile jar = new JarFile(jarFile);
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            //filter file entity
            if (!jarEntry.getName().contains(includePath)) {
                continue;
            }
            log.info("find {}", jarEntry.getName());
            //splite short filename
            String name = _substringAfter(jarEntry.getName(), includePath);
            File tarFile = new File(targetDir, name);
            //创建文件
            _createFile(jarEntry, tarFile);
            if (jarEntry.isDirectory()) {
                continue;
            }
            _transferStream(jar.getInputStream(jarEntry), tarFile);
        }
    }

    /**
     * The empty String {@code ""}.
     *
     * @since 2.0
     */
    private static final String EMPTY = "";

    private String _substringAfter(final String str, final String separator) {
        if (isEmpty(str)) {
            return str;
        }
        if (separator == null) {
            return EMPTY;
        }
        final int pos = str.indexOf(separator);
        if (pos == -1) {
            return EMPTY;
        }
        return str.substring(pos + separator.length());
    }

    private static String _substringBetween(final String str, final String open, final String close) {
        if (str == null || open == null || close == null) {
            return null;
        }
        final int start = str.indexOf(open);
        if (start == -1) {
            return _substringBetween(str, "", close);
        }
        final int end = str.indexOf(close, start + open.length());
        if (end != -1) {
            return str.substring(start + open.length(), end);
        } else {
            return str.substring(start + open.length());
        }
    }

    private static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    /**
     * 将内容流输出到文件
     *
     * @param is
     * @param file
     */
    private void _transferStream(InputStream is, File file) {
        ByteBuffer buf = ByteBuffer.allocate(512 * 10);
        try (FileChannel out = new FileOutputStream(file).getChannel();
             ReadableByteChannel in = Channels.newChannel(is)) {
            while (in.read(buf) != -1) {
                buf.flip();
                out.write(buf);
                buf.clear();
            }
        } catch (IOException e) {
            log.error("", e);
        }
    }

    /**
     * 创建文件
     *
     * @param jarEntry jar实体
     * @param file     文件实体
     * @throws IOException 抛出异常
     */
    private void _createFile(JarEntry jarEntry, File file) {
        if (file.exists()) {
            //如果是覆盖，先删除文件
            if (override) {
                file.delete();
            }
        }
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (jarEntry.isDirectory()) {
            file.mkdirs();
        } else {
            try {
                file.createNewFile();
            } catch (IOException e) {
                log.error("Create file failed:{}", file.getPath(), e);
            }
        }
    }
}
